package villa.tools.mq.views;


import java.util.Arrays;
import java.util.Enumeration;

import org.apache.xerces.impl.dv.util.HexBin;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;

import villa.tools.mq.RawMessageSender;
import villa.tools.mq.preferences.MensajesSave;
import villa.tools.mq.preferences.Propiedades;
import villa.tools.mq.util.EntityConverter;


import com.ibm.mq.MQEnvironment;
import com.ibm.mq.MQGetMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;
import com.ibm.mq.constants.CMQC;
import com.ibm.mq.constants.MQConstants;




class Actions{
	
	
	
	public static void putQMActionF(TabFolder tab)
	{
		TabControlsP tcp = (TabControlsP) tab.getItem(tab.getSelectionIndex()).getControl();
        TabControlsO tco = (TabControlsO) tcp.getItem(0).getControl();//0-Message
        TabControlsH tch = (TabControlsH) tcp.getItem(1).getControl();//0-Message
        //Date fechaAct = new Date();
        try{
        	MQSend(tco, tch);
        	tco.styledTextOTHER.setText(tco.styledTextOTHER.getText()+ "\n"+ System.currentTimeMillis()+" > Message Put > " + tco.queuePUTText.getText());
        }catch (Exception ex) {
       		tco.styledTextOTHER.setText(tco.styledTextOTHER.getText()+ "\n"+ System.currentTimeMillis()+" > Exception > "+ex.toString());
       	}
        
	}
	public static void MQSend(TabControlsO tco, TabControlsH tch) throws Exception
    {
		
		String sUrl = tco.qManagerText.getText();
		String cola = tco.queuePUTText.getText();
		String message = tco.styledTextPut.getText();
		StyledText aStyledText = tco.styledTextGet;
		tco.msgPut.replyToQueueName = tco.queueGETText.getText();
		MQQueueManager queueManager;
 		try{

 			String url[] = sUrl.split("/");
 					
 			String hostPort2 = url[2].toString();
 			Integer pos = hostPort2.indexOf("(");
 					
 			String hostName = hostPort2.substring(0, pos);
 			hostPort2 = hostPort2.substring(pos+1, hostPort2.length()-1);
 					
 			String channel = url[0].toString();
 			Integer port = Integer.parseInt(hostPort2);
 										
 			MQEnvironment.hostname = hostName;
 			MQEnvironment.port = port;
 			MQEnvironment.channel = channel;
 					
 		}catch (Exception e){
 			throw new Exception("URL Queue Manager Erronea");
 		};
 			
 		try{
 			queueManager=new MQQueueManager("");
 			MQQueue queue = queueManager.accessQueue(cola,CMQC.MQOO_OUTPUT);
 			byte aa[] = message.getBytes();
 			tco.msgPut.clearMessage();
 			tco.msgPut.format = MQConstants.MQFMT_STRING;
 			tco.msgPut.replyToQueueName = tch.replyQM.getText(); //tco.queueGETText.getText();
 			tco.msgPut.expiry = Integer.parseInt(tch.expiry.getText()); //600
 			tco.msgPut.report=14680064;
 			
 			if (tch.msgIdCheck.getSelection()){
        		tco.msgPut.messageId =HexBin.decode(tch.msgId.getText());
        	}else{
        		tco.msgPut.messageId = null;
        	}
 			
 			if (tch.correlIdCheck.getSelection()){
        		tco.msgPut.correlationId =HexBin.decode(tch.correlId.getText());
        	}else{
        		tco.msgPut.correlationId = null;
        	}
 			
 			tch.sendItem=true;
 			tco.msgPut.write(aa);
 			queue.put(tco.msgPut);
 			queue.close();
 			queueManager.disconnect();
 			tch.msgId.setText(HexBin.encode(tco.msgPut.messageId));
 			
 			if (!tco.queueGETText.getText().equals("")){
 			
	 			tco.msgGet.clearMessage();
	        	tco.msgGet.messageId = null;
	        	tco.msgGet.correlationId = tco.msgPut.messageId;
	        	tco.msgGet.setTime(60);
	        	tco.msgGet.setUrl(tco.qManagerText.getText());
	        	tco.msgGet.setCola(tco.queueGETText.getText());
	        	GetHilo hilo = new GetHilo(tco, tch);
	        	hilo.start();
 			}
 		}catch(Exception e){
 		    aStyledText.setText(e.toString());
 		}
 	}
	
	public static void MQGet(Mensaje msg) throws Exception
    {
		
		String sUrl = msg.getUrl();
		String cola = msg.getCola();
		//StyledText aStyledText = msg.getStyledText();
		
		MQQueueManager queueManager;
 		try{

 			String url[] = sUrl.split("/");
 					
 			String hostPort2 = url[2].toString();
 			Integer pos = hostPort2.indexOf("(");
 					
 			String hostName = hostPort2.substring(0, pos);
 			hostPort2 = hostPort2.substring(pos+1, hostPort2.length()-1);
 					
 			String channel = url[0].toString();
 			Integer port = Integer.parseInt(hostPort2);
 										
 			MQEnvironment.hostname = hostName;
 			MQEnvironment.port = port;
 			MQEnvironment.channel = channel;
 					
 		}catch (Exception e){
 			throw new Exception("URL Queue Manager Erronea");
 		};
 		try{
 			queueManager=new MQQueueManager("");
 			MQQueue queue = queueManager.accessQueue(cola,CMQC.MQOO_INPUT_SHARED);
 			MQGetMessageOptions msgOpt = new MQGetMessageOptions();
 			msgOpt.waitInterval = msg.getTime()*1000;//milisegundos;
 			msgOpt.options = CMQC.MQGMO_WAIT;
 			queue.get(msg,msgOpt);
 			queue.close();
 			queueManager.disconnect();
 		}catch(Exception e){
 			throw new Exception(e.toString());
 		}
 	}
	
	public static void getQMActionF(TabFolder tab)
	{
		TabControlsP tcp = (TabControlsP) tab.getItem(tab.getSelectionIndex()).getControl();
        TabControlsO tco = (TabControlsO) tcp.getItem(0).getControl();//0-Message
        TabControlsH tch = (TabControlsH) tcp.getItem(1).getControl();//0-Message
        //Date fechaAct = new Date();
        try{
        	tco.msgGet.clearMessage();
        	
        	if (tch.msgIdCheck.getSelection()){
        		tco.msgGet.messageId =HexBin.decode(tch.msgId.getText());
        	}else{
        		tco.msgGet.messageId = null;
        	}
 			
 			if (tch.correlIdCheck.getSelection()){
 				tco.msgGet.correlationId =HexBin.decode(tch.correlId.getText());
        	}else{
        		tco.msgGet.correlationId = null;
        	}
        	tch.sendItem=false;
        	tco.msgGet.setTime(0);
        	tco.msgGet.setUrl(tco.qManagerText.getText());
        	tco.msgGet.setCola(tco.queueGETText.getText());
        	GetHilo hilo = new GetHilo(tco, tch);
        	hilo.start();
        }catch (Exception ex) {
       		tco.styledTextOTHER.setText(tco.styledTextOTHER.getText()+ "\n"+ System.currentTimeMillis()+" > Exception > "+ex.toString());
       	}
        
	}
	
	public static void printMessage(TabControlsO tco, TabControlsH tch)
	{
		//Date fechaAct = new Date();
		try{
			if (tco.msgGet.getErr().equals("")){
				byte[] buffer = new byte [tco.msgGet.getMessageLength()]; 
				tco.msgGet.readFully(buffer);
				String msg1 = new String(buffer);
				tco.styledTextGet.setText(msg1);
				if (tch.sendItem == false) {
					tch.correlId.setText(HexBin.encode(tco.msgGet.correlationId));
					tch.msgId.setText(HexBin.encode(tco.msgGet.messageId));
					tch.expiry.setText(String.valueOf(tco.msgGet.expiry));
					tch.replyQM.setText(tco.msgGet.replyToQueueName);
				}
				
				tco.styledTextOTHER.setText(tco.styledTextOTHER.getText()+ "\n"+ System.currentTimeMillis()+" > Message Get > " + tco.msgGet.getCola());
			}else{
				tco.styledTextOTHER.setText(tco.styledTextOTHER.getText()+ "\n"+ System.currentTimeMillis()+" > Exception > "+tco.msgGet.getErr());
			}
		}catch (Exception e) {
			tco.styledTextOTHER.setText(tco.styledTextOTHER.getText()+ "\n"+ System.currentTimeMillis()+" > Exception > "+e.toString());
		}
	}
	
	public static void indentActionF(TabFolder tab)
	{
		TabControlsP tcp = (TabControlsP) tab.getItem(tab.getSelectionIndex()).getControl();
        TabControlsO tco = (TabControlsO) tcp.getItem(0).getControl();//1-Message
        StyledText styledText = null;
        if (tco.styledTextOTHER.isFocusControl()) {
    		styledText = tco.styledTextOTHER;
    	} else if (tco.styledTextPut.isFocusControl()) {
    		styledText = tco.styledTextPut;
    	} else if (tco.styledTextGet.isFocusControl()) {
    		styledText = tco.styledTextGet;
    	} else {
    		return;
    	}
        String tmpString = styledText.getText();
    	String formattedString = RawMessageSender.prettyPrint(tmpString);
    	styledText.setText(formattedString);
    	tco.colorXml(styledText);
                
	}
	
	public static void escapeXMLActionF(TabFolder tab)
	{
		TabControlsP tcp = (TabControlsP) tab.getItem(tab.getSelectionIndex()).getControl();
        TabControlsO tco = (TabControlsO) tcp.getItem(0).getControl();//1-Message
        StyledText styledText = null;
        if (tco.styledTextOTHER.isFocusControl()) {
    		styledText = tco.styledTextOTHER;
    	} else if (tco.styledTextPut.isFocusControl()) {
    		styledText = tco.styledTextPut;
    	} else if (tco.styledTextGet.isFocusControl()) {
    		styledText = tco.styledTextGet;
    	} else {
    		return;
    	}
        String tmpString = styledText.getSelectionText();
    	String escapedString = EntityConverter.escapeString(tmpString);
    	Point sel = styledText.getSelection();
    	int start = sel.x;
    	int length = sel.y - sel.x;
    	styledText.replaceTextRange(start, length, escapedString);
    	styledText.setSelection(start, start + escapedString.length());
    	tco.colorXml(styledText);

                
	}
	
	public static void unescapeXMLActionF(TabFolder tab)
	{
		TabControlsP tcp = (TabControlsP) tab.getItem(tab.getSelectionIndex()).getControl();
        TabControlsO tco = (TabControlsO) tcp.getItem(0).getControl();//1-Message
        StyledText styledText = null;
        if (tco.styledTextOTHER.isFocusControl()) {
    		styledText = tco.styledTextOTHER;
    	} else if (tco.styledTextPut.isFocusControl()) {
    		styledText = tco.styledTextPut;
    	} else if (tco.styledTextGet.isFocusControl()) {
    		styledText = tco.styledTextGet;
    	} else {
    		return;
    	}
    	String tmpString = styledText.getSelectionText();
    	String unescapedString = EntityConverter.unescapeString(tmpString);

    	Point sel = styledText.getSelection();
    	int start = sel.x;
    	int length = sel.y - sel.x;
    	styledText.replaceTextRange(start, length, unescapedString);
    	styledText.setSelection(start, start + unescapedString.length());
    	tco.colorXml(styledText); 
       
	}
	
	public static void newActionF(TabFolder tab)
	{
		addTab(tab);
    	tab.setSelection(tab.getItemCount() - 1);
    	TabControlsP tcp = (TabControlsP)tab.getItem(tab.getSelectionIndex()).getControl();
		TabControlsO tco = (TabControlsO)tcp.getItem(0).getControl();//message
    	loadListF(tco.queuePUTCombo);
    }
	
	public static void addTab(TabFolder tab) {
		TabItem ti1 = new TabItem(tab, SWT.NONE);
	    TabControlsP tabControlsP = new TabControlsP(tab,SWT.NONE);
	    ti1.setControl(tabControlsP);
	    tabControlsP.setTabItem(ti1);
		
		
	}
	
	public static void saveActionF(TabFolder tab) {
		String nombre;
		String valor;
		Propiedades.getInstancia().cleanProperties();
		nombre = "cont";
		valor = String.valueOf(tab.getItemCount());
		Propiedades.getInstancia().setPropiedad(nombre,valor);
		nombre = "wrap";
		valor = String.valueOf(Basic.getInstancia().getWrap());
		Propiedades.getInstancia().setPropiedad(nombre,valor);
		nombre = "indent";
		valor = String.valueOf(Basic.getInstancia().getIndent());
		Propiedades.getInstancia().setPropiedad(nombre,valor);
		
		for(int i =0;i<tab.getItemCount();i++){
			TabControlsP tcp = (TabControlsP)tab.getItem(i).getControl();
			TabControlsO tco = (TabControlsO)tcp.getItem(0).getControl();//message
			nombre = "tab"+String.valueOf(i)+"qManagerText";
			valor = tco.qManagerText.getText();
			Propiedades.getInstancia().setPropiedad(nombre,valor);
			nombre = "tab"+String.valueOf(i)+"queueGETText";
			valor = tco.queueGETText.getText();
			Propiedades.getInstancia().setPropiedad(nombre,valor);
			nombre = "tab"+String.valueOf(i)+"queuePUTText";
			valor = tco.queuePUTText.getText();
			Propiedades.getInstancia().setPropiedad(nombre,valor);
			nombre = "tab"+String.valueOf(i)+"styledTextGet";
			valor = tco.styledTextGet.getText();
			Propiedades.getInstancia().setPropiedad(nombre,valor);
			nombre = "tab"+String.valueOf(i)+"styledTextPut";
			valor = tco.styledTextPut.getText();
			Propiedades.getInstancia().setPropiedad(nombre,valor);
		}
		
		Propiedades.getInstancia().savePropiedad();

	}
	
	public static void saveMensajesF(String nombre, String valor) {
		
		//MensajesSave.getInstancia().cleanProperties();
		
		//TabControlsP tcp = (TabControlsP) tab.getItem(tab.getSelectionIndex()).getControl();
		//TabControlsO tco = (TabControlsO)tcp.getItem(0).getControl();//message
			
		MensajesSave.getInstancia().setPropiedad(nombre,valor);
		MensajesSave.getInstancia().savePropiedad();

	}
	
	public static void loadActionF(TabFolder tab) {
		String nombre;
		String valor;
		int cont;
		

		//valor = MensajesSave.getInstancia().get;
		
		nombre = "cont";
		valor = Propiedades.getInstancia().getPropiedad(nombre);
		if (valor.equals("")){
			cont = 0;
		}else{
			cont = Integer.parseInt(valor);
			nombre = "wrap";
			valor = Propiedades.getInstancia().getPropiedad(nombre);
			Basic.getInstancia().setWrap(Boolean.parseBoolean(valor));
			nombre = "indent";
			valor = Propiedades.getInstancia().getPropiedad(nombre);
			Basic.getInstancia().setIndent(Boolean.parseBoolean(valor));
		}
		for(int i =0;i<cont;i++){
			TabItem ti1 = new TabItem(tab, SWT.NONE);
		    TabControlsP tcp = new TabControlsP(tab,SWT.NONE);
		    ti1.setControl(tcp);
			TabControlsO tco = (TabControlsO)tcp.getItem(0).getControl();//message
			nombre = "tab"+String.valueOf(i)+"qManagerText";
			valor = Propiedades.getInstancia().getPropiedad(nombre);
			tco.qManagerText.setText(valor);
			nombre = "tab"+String.valueOf(i)+"styledTextGet";
			valor = Propiedades.getInstancia().getPropiedad(nombre);
			tco.styledTextGet.setText(valor);
			tco.styledTextGet.clearUndoStack();
			nombre = "tab"+String.valueOf(i)+"styledTextPut";
			valor = Propiedades.getInstancia().getPropiedad(nombre);
			tco.styledTextPut.setText(valor);
			tco.styledTextPut.clearUndoStack();
			tcp.setTabItem(ti1);
			nombre = "tab"+String.valueOf(i)+"queueGETText";
			valor = Propiedades.getInstancia().getPropiedad(nombre);
			tco.queueGETText.setText(valor);
			nombre = "tab"+String.valueOf(i)+"queuePUTText";
			valor = Propiedades.getInstancia().getPropiedad(nombre);
			tco.queuePUTText.setText(valor);
			int len = tco.queuePUTText.getText().length();
			if (len > 20) {
				ti1.setText(tco.queuePUTText.getText(0, 8) + "..." + tco.queuePUTText.getText(len - 9, len - 1));
			} else {
				ti1.setText(tco.queuePUTText.getText());
			}
			loadListF(tco.queuePUTCombo);
			tco.queuePUTCombo.setText(valor);
		}
		if (tab.getItemCount() == 0) {
			Actions.addTab(tab);
		}
		

	}
	
	public static void loadListF(Combo queuePUTCombo) {
		Enumeration keys = MensajesSave.getInstancia().getEnumeration();
		String actual = queuePUTCombo.getText();
		queuePUTCombo.removeAll();
		
		while (keys.hasMoreElements()) { 
			String key = (String)keys.nextElement();
			if (!key.contains("_COLA")){
				queuePUTCombo.add(key);
			}
		}
		
		String[] items = queuePUTCombo.getItems();
        Arrays.sort(items);
        queuePUTCombo.setItems(items);
		
		queuePUTCombo.setText(actual);
		
	}
	
	
	public static void closeActionF(TabFolder tab)
	{
		tab.getItem(tab.getSelectionIndex()).dispose();
	}
	
	public static void indentToggleActionF(boolean val)
	{
		Basic.getInstancia().setIndent(val);
	}
	
	public static void wrapToggleActionF(boolean val)
	{
		Basic.getInstancia().setWrap(val);
	}
	
}

